package com.bjqg.bjqg01.bjqg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bjqg.bjqg01.bjqg.R;
import com.bjqg.bjqg01.bjqg.bean.UserLoginBean;
import com.bjqg.bjqg01.bjqg.dialog.DialogCallback;
import com.bjqg.bjqg01.bjqg.dialog.IntentLoginDialog;
import com.bjqg.bjqg01.bjqg.utils.Constant;
import com.bjqg.bjqg01.bjqg.utils.SPHelper;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by bjqg01 on 2017/12/8.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String SP_NAME = "username";
    private EditText username;
    private EditText userpwd;
    private TextView forgetpwd;
    private TextView regist;
    private Button login;
    //用户名,密码textview值
    private String getusername;
    private String getuserpwd;
    private String[] split1;
    IntentLoginDialog.Builder dialog;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {

            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }

            //地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
            address = amapLocation.getAddress();
            //国家信息
            country = amapLocation.getCountry();


        }
    };
    private String address;
    private String country;
    private AMapLocationClientOption mLocationOption;
    private SPHelper spHelper;
    AutoRelativeLayout picfather;
    AutoLinearLayout alfather;
    TranslateAnimation translateAnimation;
    TranslateAnimation translateAnimation1;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login2);

        //注册监听函数
        initView();
        setOnClickListener();
        dialog = new IntentLoginDialog.Builder(this);
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());

        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        initData();
//        doLogin();
    }

    //高德地图参数配置
    private void initData() {

//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        AMapLocationClientOption option = new AMapLocationClientOption();

        //获取最近3s内精度最高的一次定位结果：
//设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);

        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
//        mLocationOption.isNeedAddress(true);

        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);

        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位

    }

    @Override
    protected void onStart() {
        super.onStart();
        mLocationClient.startLocation();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stopLocation();
    }

    private void setOnClickListener() {
        forgetpwd.setOnClickListener(this);
        regist.setOnClickListener(this);
        login.setOnClickListener(this);
    }

    private void initView() {
        username = (EditText) findViewById(R.id.user_name);
        userpwd = (EditText) findViewById(R.id.user_password);
        forgetpwd = (TextView) findViewById(R.id.tv_forget_pwd);
        regist = (TextView) findViewById(R.id.tv_regist);
        login = (Button) findViewById(R.id.login);
        picfather = (AutoRelativeLayout) findViewById(R.id.pic_father);
        alfather = (AutoLinearLayout) findViewById(R.id.al_father);
        spHelper = new SPHelper(getApplicationContext(), Constant.SPLOGIN);
        String spusername = (String) spHelper.getSharedPreference(SP_NAME, "");
        if (spusername.length() != 0) {
            username.setText(spusername);
        }

        username.setText("18630939453");
        userpwd.setText("654321");
        login.setBackgroundResource(R.drawable.bule_rec_bg);


        translateAnimation = new TranslateAnimation(0, 0, -500, 0);
        translateAnimation.setDuration(500);
        picfather.startAnimation(translateAnimation);

        translateAnimation1 = new TranslateAnimation(0, 0, 500, 0);
        translateAnimation1.setDuration(500);
        alfather.startAnimation(translateAnimation1);

        username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    if (userpwd.getText().toString().length() > 0) {
                        login.setBackgroundResource(R.drawable.bule_rec_bg);
                    } else {
                        login.setBackgroundResource(R.drawable.gray_rect_bg);
                    }
                } else {
                    login.setBackgroundResource(R.drawable.gray_rect_bg);
                }
            }
        });

        userpwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    if (username.getText().toString().trim().length() > 0) {
                        login.setBackgroundResource(R.drawable.bule_rec_bg);
                    } else {
                        login.setBackgroundResource(R.drawable.gray_rect_bg);
                    }
                } else {
                    login.setBackgroundResource(R.drawable.gray_rect_bg);
                }
            }
        });

    }


    private void doLogin() {
        if (getusername == null && getusername.equals("") && getuserpwd == null && getuserpwd.equals("")) {
            Toast.makeText(getApplicationContext(), "用户名或密码不能为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        getokgo(getUrl());
    }


    private void UpdateAddress() {
        getokgo(getUrlUpdateDengXinXi());
    }

    private void getokgo(String url) {
//        OkGo.<String>get(url)
//                .tag(this)
//                .execute(new DialogCallback(this) {
//                    @Override
//                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
//                        String str = "<string xmlns=\"http://tempuri.org/\">";
//                        String strend = "</string>";
//                        String strerror = "{\"ds\":{}}";
//                        String[] split = response.body().toString().split(str);
//                        split1 = split[1].split(strend);
//
//                        if (strerror.equals(split1[0])) {
//                            Toast.makeText(LoginActivity.this, "未找到该用户，请确认手机号", Toast.LENGTH_SHORT).show();
//                        } else if ("记录登录位置及时间".equals(split1[0])) {
//
//                        } else {
//                            Gson gson = new Gson();
//                            UserLoginBean refreshinfo = gson.fromJson(split1[0], UserLoginBean.class);
//                            List<UserLoginBean.DsBean> ds = refreshinfo.getDs();
//                            if (getusername.equals(ds.get(0).getPhoneNum()) && getuserpwd.equals(ds.get(0).getPwd())) {
//                                UpdateAddress();
//                                spHelper.put(SP_NAME, getusername);

//                            } else {
//                                Toast.makeText(LoginActivity.this, "用户名或密码不正确", Toast.LENGTH_LONG).show();
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(com.lzy.okgo.model.Response<String> response) {
//                        super.onError(response);
//                        Toast.makeText(LoginActivity.this, "服务器正忙，请稍后再试!", Toast.LENGTH_SHORT).show();
//                    }
//                });
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, NewHomeActivity2.class);
        startActivity(intent);
        finish();
    }

    @android.support.annotation.NonNull
    private String getUrlUpdateDengXinXi() {
        StringBuffer sb = new StringBuffer();
        getusername = username.getText().toString().trim();
        getuserpwd = userpwd.getText().toString().trim();
        if (getusername != null && getusername != "" && !getusername.equals("")) {
            String usernamecode = URLEncoder.encode(getusername);
            sb.append("PhoneNum=" + usernamecode);
        }
//        address = "测试地址"+address;
        String jyxmcode = URLEncoder.encode(country + address);
        sb.append("&DengPlace=" + jyxmcode);
//        if (addr!=null&&addr!=""&&!addr.equals("")){
//            if (sb.toString().length()!=0)sb.append("&");
//            String jyxmcode = URLEncoder.encode(addr);
//            sb.append("DengPlace="+jyxmcode);
//        }

        String url = Constant.BASEURL + Constant.UPDATEDENGXINXI + "?" + sb.toString();
        Log.e("----------error", "失败：------------------------" + url);
        return url;
    }

    @android.support.annotation.NonNull
    private String getUrl() {
        StringBuffer sb = new StringBuffer();
        getusername = username.getText().toString().trim();
        getuserpwd = userpwd.getText().toString().trim();
        if (getusername != null && getusername != "" && !getusername.equals("")) {
            String usernamecode = URLEncoder.encode(getusername);
            sb.append("phonenum=" + usernamecode);
        }
        if (getuserpwd != null && getuserpwd != "" && !getuserpwd.equals("")) {
            if (sb.toString().length() != 0) sb.append("&");
            String jyxmcode = URLEncoder.encode(getuserpwd);
            sb.append("jyxm=" + jyxmcode);
        }
        String url = Constant.BASEURL + Constant.SELECTAPPUSER + "?" + sb.toString();
        Log.e("----------error", "失败：------------------------" + url);
        return url;
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.tv_forget_pwd://忘记密码
                intent = new Intent();
                intent.setClass(this, ForgetPawActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_regist://新用户注册
                intent = new Intent();
                intent.setClass(this, RegistUserActivity.class);
                startActivity(intent);
                break;
            case R.id.login://登陆
                getusername = username.getText().toString();
                getuserpwd = userpwd.getText().toString();
                if (!checkCellphone(getusername)) {
                    Toast.makeText(getApplicationContext(), "手机号不合法", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (getuserpwd.length() == 0) {
                    Toast.makeText(getApplicationContext(), "请填写密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                doLogin();
                break;

        }
    }

    /**
     * 验证手机号码
     * <p>
     * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147、182
     * 联通号码段:130、131、132、136、185、186、145
     * 电信号码段:133、153、180、189、177
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,1,2,3,5-9])|(177))\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(cellphone);
        return matcher.matches();
    }
}
